package com.tgy.springmvc.controller;

import com.tgy.springmvc.constant.WebMvcConstant;
import com.tgy.springmvc.pojo.UserVO;
import com.tgy.springmvc.util.RequestUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @Author: tgy
 * @Date: 2020-08-24 09:54
 */
@Controller
public class LoginController {


    @GetMapping("/to-login")
    public String showLogin(Model model, HttpServletRequest request){

        Object error = request.getAttribute("error");

        if (!StringUtils.isEmpty(error)){

            model.addAttribute("error",error);
        }

        return "login";
    }

    @PostMapping("/login")
    public String toLogin(String username, String password, HttpServletRequest request){


        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {

            request.setAttribute("error","请输入用户名密码");
            request.setAttribute("redirectURL","/to-login");
            return "error";
        }


        if (!("zhangsan".equals(username) && "123".equals(password))){

            request.setAttribute("error","用户名密码错误");
            request.setAttribute("redirectURL","/to-login");
            return "error";
        }

        UserVO userVO = new UserVO();

        userVO.setName(username);
        userVO.setEmail("79034234234@111");
        userVO.setDescription("啊哈哈");
        RequestUtil.setSession(WebMvcConstant.SESSION_USER_KEY, userVO);

        Object redirectUrl = RequestUtil.getSession(WebMvcConstant.REDIRECT_URL_KEY);

        if (StringUtils.isEmpty(redirectUrl)){

            return "redirect:/admin/index";
        }else {

            RequestUtil.setSession(WebMvcConstant.REDIRECT_URL_KEY, null);
            return "redirect:" + redirectUrl;
        }

    }

    @GetMapping("/admin/logout")
    public String logout(){

        RequestUtil.setSession(WebMvcConstant.SESSION_USER_KEY,null);
        return "redirect:/to-login";
    }


}
